
from flask import Blueprint, render_template
from blog.model.Article import Article
import pygal
import datetime


#  创建蓝图 第一个参数为蓝图的名字
home = Blueprint('home', __name__)


@home.route('/index')
def index():
    range = 7
    time_curr = datetime.date.today()
    list_y_date = []  # y轴数据
    list_x_date = []  # x轴数据
    counter = 0
    while counter < range:
        time_start = time_curr + datetime.timedelta(days=-counter)
        time_end = time_start + datetime.timedelta(days=1)
        c = Article.query.filter(Article.post_time >= time_start, Article.post_time <= time_end).count()
        list_y_date.append(c)  # 添加y轴数据
        list_x_date.append(time_start)  # 添加x轴数据
        counter += 1

    list_x_date.reverse()  # list_date列表反转，使时间正序
    list_y_date.reverse()  # list_y_date列表反转，使数据同步x轴

    # 折线图
    line_chart = pygal.Line()
    line_chart.title = '最近' + str(range) + '天每天发布博客数量走势图'
    line_chart.x_title = '日期'
    line_chart.y_title = '博客数量'
    line_chart.x_labels = list_x_date  # x轴数据
    line_chart.x_label_rotation = 20  # x轴的文字旋转20度
    line_chart.show_y_guides = True  # 默认显示y参考虚线
    line_chart.add("博客数", list_y_date)  # y轴数据
    # line_chart.render_to_file('my_chart.svg')  # 保存到本地，格式必须是svg

    return render_template('home/index.html', chart=line_chart)


